class AjaxUtils {
  constructor() {
    this.xhr = new XMLHttpRequest();
  }

  sendRequest(requestConfig) {
    const { url, method = 'GET', headers = {}, data = null } = requestConfig;

    return new Promise((resolve, reject) => {
      this.xhr.open(method, url, true);

      // 设置请求头
      Object.keys(headers).forEach((key) => {
        this.xhr.setRequestHeader(key, headers[key]);
      });

      this.xhr.onreadystatechange = () => {
        if (this.xhr.readyState === XMLHttpRequest.DONE) {
          if (this.xhr.status >= 200 && this.xhr.status < 400) {
            resolve(this.xhr.responseText);
          } else {
            reject(this.xhr.status);
          }
        }
      };

      this.xhr.onerror = () => {
        reject(this.xhr.status);
      };

      this.xhr.send(data);
    });
  }

  abort() {
    if (this.xhr) {
      this.xhr.abort();
    }
  }
}

function ajax() {
  return new AjaxUtils();
}